package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.CollectGoodsData;
import cn.com.ejiakanghu.dto.CollectStoreInfo;
import cn.com.ejiakanghu.dto.EnumCollectType;
import cn.com.ejiakanghu.dto.PageData;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.GoodsConstant;
import org.linlinjava.litemall.db.vo.app.StoreGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户收藏服务
 */
@Component
public class CollectManager {
    private final Log logger = LogFactory.getLog(CollectManager.class);

    @Autowired
    private LitemallCollectService collectService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private AgedmallStoreService agedmallStoreService;
    @Autowired
    private AgedmallGoodsDeductionConfService agedmallGoodsDeductionConfService;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private AgedmallStoreGoodsService agedmallStoreGoodsService;
    @Autowired
    private AgedmallHospitalSendService agedmallHospitalSendService;


    /**
     * 用户收藏列表
     *
     * @param userId 用户ID
     * @param type   类型，如果是0则是商品收藏，如果是1则是专题收藏, 如果是2则是店铺收藏
     * @param page   分页页数
     * @param limit  分页大小
     * @return 用户收藏列表
     */
    public BaseResult list(Integer userId,
                           String keyword,
                           Byte type,
                           Integer page,
                           Integer limit,
                           String sort,
                           String order) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        List<LitemallCollect> collectList = collectService.fuzzyQueryByType(userId, keyword, type, page, limit, sort, order);
        PageInfo<LitemallCollect> pagedList = PageInfo.of(collectList);

        List<Long> collectIdList = new ArrayList<>();
        collectList.stream().forEach(c -> {
            collectIdList.add(Long.valueOf(c.getValueId().intValue()));
        });
        if (EnumCollectType.STORE.getType() == type) {
            //店铺收藏
            PageData<CollectStoreInfo> pageData = new PageData<>();
            if (collectIdList.size() == 0) {
                return RespUtil.success(pageData);
            }
            List<AgedmallStore> storeList = agedmallStoreService.getStoreListByIds(collectIdList);
            List<CollectStoreInfo> collectStoreInfoList = new ArrayList<>();
            storeList.stream().forEach(s -> {
                CollectStoreInfo collectStoreInfo = CollectStoreInfo.getInstance(s);
                // 获取上架售卖和租赁商品数
                int saleGoodsCount = goodsService.countByStoreId(s.getId().intValue(), GoodsConstant.GOODS_TYPE_SALE);
                int leaseGoodsCount = goodsService.countByStoreId(s.getId().intValue(), GoodsConstant.GOODS_TYPE_LEASE);
                collectStoreInfo.setSaleGoodsCount(saleGoodsCount);
                collectStoreInfo.setLeaseGoodsCount(leaseGoodsCount);
                collectStoreInfoList.add(collectStoreInfo);
            });
            pageData.setNowPage(page);
            pageData.setTotalPage(pagedList.getPages());
            pageData.setTotalRows((int) pagedList.getTotal());
            pageData.setRows(collectStoreInfoList);
            return RespUtil.success(pageData);
        } else if (EnumCollectType.GOODS.getType() == type) {
            List<CollectGoodsData> rowDataList = new ArrayList<>();
            for (LitemallCollect collect : collectList) {
                CollectGoodsData rowData = new CollectGoodsData();
                if (type == (byte) 0) {
                    //查询商品信息
                    StoreGoodsVo goods = agedmallStoreGoodsService.getStoreGoodsById(collect.getValueId());
                    if (goods == null) {
                        continue;
                    }
                    // 是否支持医院小时达
                    List<AgedmallHospitalSend> hospitalSends = agedmallHospitalSendService.getByStoreAndGoods(goods.getStoreId(), goods.getId());
                    goods.setIsHospital(hospitalSends.size() > 0 ? 1 : 0);
                    rowData.init(goods);
                    // 抵扣金
                    BigDecimal deductNum = agedmallGoodsDeductionConfService.getDeductNumByGoods(goods);
                    if (null != deductNum) {
                        rowData.setDeductNum(deductNum.doubleValue());
                    }
                    // 省市信息
                    AgedmallStore store = agedmallStoreService.findStoreById(goods.getStoreId());
                    if (null != store) {
                        rowData.setProvince(store.getProvinceName());
                        rowData.setCity(store.getCityName());
                    }
                } else {
                    //查询专题信息
                }
                rowDataList.add(rowData);
            }
            PageData<CollectGoodsData> pageData = new PageData<>();
            pageData.setNowPage(page);
            pageData.setTotalPage(pagedList.getPages());
            pageData.setTotalRows((int) pagedList.getTotal());
            pageData.setRows(rowDataList);
            return RespUtil.success(pageData);
        }
        return RespUtil.success();
    }

    public BaseResult delete(Integer userId, Byte type, Integer valueId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        if (!ObjectUtils.allNotNull(type, valueId)) {
            return RespUtil.badArgument();
        }

        LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);

        if (collect != null) {
            collectService.deleteById(collect.getId());
            return RespUtil.success();
        }
        return RespUtil.success("已删除");
    }

    /**
     * 用户收藏添加或删除
     * <p>
     * 如果商品没有收藏，则添加收藏；如果商品已经收藏，则删除收藏状态。
     *
     * @param userId 用户ID
     * @param body   请求内容，{ type: xxx, valueId: xxx }
     * @return 操作结果
     */
    public BaseResult add(Integer userId, String body) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        Byte type = JacksonUtil.parseByte(body, "type");
        Integer valueId = JacksonUtil.parseInteger(body, "valueId");
        if (!ObjectUtils.allNotNull(type, valueId)) {
            return RespUtil.badArgument();
        }

        LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);

        if (collect != null) {
            return RespUtil.success("已收藏");
        }

        Map<String, Object> data = new HashMap<>();
        if (EnumCollectType.STORE.getType() == type) {
            //收藏店铺
            AgedmallStore agedmallStore = agedmallStoreService.findStoreById(valueId);
            if (null == agedmallStore) {
                return RespUtil.badArgumentValue();
            }
            CollectStoreInfo storeInfo = CollectStoreInfo.getInstance(agedmallStore);
            data.put("stores", storeInfo);
        } else if (EnumCollectType.GOODS.getType() == type) {
            //商品
            StoreGoodsVo goods = agedmallStoreGoodsService.getStoreGoodsById(valueId);
            if (null == goods) {
                return RespUtil.badArgumentValue();
            }
            CollectGoodsData rowData = new CollectGoodsData();
            rowData.init(goods);
        }

        collect = new LitemallCollect();
        collect.setUserId(userId);
        collect.setValueId(valueId);
        collect.setType(type);
        collectService.add(collect);

        return RespUtil.success(data);
    }

    public BaseResult isCollect(Integer userId, Integer id, Byte type) {
        if (userId == null) {
            return RespUtil.unlogin();
        }

        int isCollect = collectService.isCollect(userId, id, type);

        Map<String, Object> data = new HashMap<>();
        data.put("isCollect", isCollect);
        return RespUtil.success(data);
    }
}